import { Table, Button, message, Modal, Tag } from 'antd';
import { useState, useEffect } from 'react';
import type { TableProps } from 'antd';
import PageLayout from '../../components/Layout/PageLayout';
import { getMyReservations, deleteReadingRoomReservation } from '@/api/readingRoomReservationController';

// 定义返回数据类型
interface ReservationRecord {
  id: string;
  roomName: string;
  seatNumber: number;
  startTime: string;
  endTime: string;
  status?: 'using' | 'appointed' | 'finished';
  appointmentTime?: string;
}

const MySeat = () => {
  const [seatList, setSeatList] = useState<ReservationRecord[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchSeatList = async () => {
    try {
      setLoading(true);
      const res = await getMyReservations();
      if (res.code === 200) {
        // 处理状态：如果当前时间在开始和结束时间之间，则为使用中
        const list = res.data.map(item => {
          const now = new Date().getTime();
          const startTime = new Date(item.startTime).getTime();
          const endTime = new Date(item.endTime).getTime();
          
          let status: 'using' | 'appointed' | 'finished';
          if (now < startTime) {
            status = 'appointed';
          } else if (now >= startTime && now <= endTime) {
            status = 'using';
          } else {
            status = 'finished';
          }
          
          return {
            ...item,
            status,
            appointmentTime: `${item.startTime.split(' ')[1]}-${item.endTime.split(' ')[1]}`,
          };
        });
        setSeatList(list);
      } else {
        message.error(res.message || '获取座位列表失败');
      }
    } catch (error) {
      message.error('获取座位列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSeatList();
  }, []);

  const columns: TableProps<ReservationRecord>['columns'] = [
    {
      title: '阅览室',
      dataIndex: 'roomName',
      key: 'roomName',
    },
    {
      title: '座位编号',
      dataIndex: 'seatNumber',
      key: 'seatNumber',
    },
    {
      title: '预约时间',
      dataIndex: 'appointmentTime',
      key: 'appointmentTime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: 'using' | 'appointed' | 'finished') => {
        const statusMap = {
          using: { color: 'green', text: '使用中' },
          appointed: { color: 'gold', text: '已预约' },
          finished: { color: 'blue', text: '已完成' },
        };
        const { color, text } = statusMap[status];
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button 
          type="link" 
          danger 
          disabled={record.status === 'finished'}
          onClick={() => handleCancelSeat(record)}
        >
          退座
        </Button>
      ),
    },
  ];

  const handleCancelSeat = (record: ReservationRecord) => {
    Modal.confirm({
      title: '确认退座',
      content: `确定要退掉 ${record.roomName} 的 ${record.seatNumber} 号座位吗？`,
      onOk: async () => {
        try {
          const res = await deleteReadingRoomReservation({ id: record.id });
          if (res.code === 200) {
            message.success('退座成功');
            fetchSeatList(); // 重新获取列表
          } else {
            message.error(res.message || '退座失败');
          }
        } catch (error) {
          message.error('退座失败');
        }
      },
    });
  };

  return (
    <PageLayout>
      <div className="p-6">
        <div className="bg-white rounded-lg shadow">
          <Table
            loading={loading}
            columns={columns}
            dataSource={seatList}
            rowKey="id"
            pagination={false}
          />
        </div>
      </div>
    </PageLayout>
  );
};

export default MySeat; 